package main

import (
	"context"
	"errors"
	"flag"
	"fmt"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
	"nvr-http-proxy/internal/constant"
	"nvr-http-proxy/internal/initialize"
	"nvr-http-proxy/internal/initialize/config"
	"nvr-http-proxy/internal/middlewares"
	"nvr-http-proxy/internal/proxy"
	router "nvr-http-proxy/internal/router"
	"os"
	"os/signal"
	"syscall"
	"time"
)

func main() {

	// 定义一个接收文件路径的标志
	jsonFilePath := flag.String("config", "", "the path to the JSON file")
	flag.Parse()
	if *jsonFilePath == "" {
		fmt.Println("Please provide a valid config file path using -config flag.")
		*jsonFilePath = constant.NvrConfigPath
	}
	//初始化日志
	initialize.InitLogger()
	//读取本地文件实现
	//nvrConfig := config.NewNvrConfig(*jsonFilePath)
	//调用edge接口获取
	nvrConfig := config.NewNvrEdge(constant.EdgeNvrConfigHttpApi)
	login := initialize.NewLogin(nvrConfig)
	nvr, err := login.InitLoginNvr()
	if err != nil {
		return
	}
	newProxy := proxy.NewProxy(nvr)

	r := gin.Default()
	//解决跨域问题
	r.Use(middlewares.Cors())
	// 添加中间件用于移除 "/proxy" 前缀
	r.Use(middlewares.DeleteProxyPrefix())

	srv := &http.Server{
		Addr:    ":13523",
		Handler: r.Handler(),
	}
	router.InitRouter(r, newProxy)
	go func() {
		// service connections
		if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
			log.Fatalf("listen: %s\n", err)
		}
	}()
	// Wait for interrupt signal to gracefully shutdown the server with
	// a timeout of 5 seconds.
	quit := make(chan os.Signal, 1)
	// kill (no param) default send syscall.SIGTERM
	// kill -2 is syscall.SIGINT
	// kill -9 is syscall. SIGKILL but can"t be catch, so don't need add it
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit
	log.Println("Shutdown Server ...")

	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	if err := srv.Shutdown(ctx); err != nil {
		log.Fatal("Server Shutdown:", err)
	}
	select {
	case <-ctx.Done():
		log.Println("timeout of 5 seconds.")
	}
	log.Println("Server exiting")
}
